package mod.ul.ed;

import java.util.List;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentSender;
import android.content.IntentSender.SendIntentException;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class MainActivity extends Activity {
	final String MODULED_GET_TEXT = "mod.ul.ed.GET_TEXT";
	final String MODULED_MODULES = "mod.ul.ed.MODULES";
	final int REQUEST_GET_TEXT = 0x1;
	
	TextView hello;
	String items_pkg[];
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        findViewById(R.id.get_text).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent call = new Intent(MODULED_GET_TEXT);
				IntentSender sender = PendingIntent.getActivity(getApplicationContext(), REQUEST_GET_TEXT, call, 0).getIntentSender();
		        
				try {
					startIntentSenderForResult(sender, REQUEST_GET_TEXT, call, 0, 0, 0);
				} catch (SendIntentException e) {
					Log.e("Exception", "SendIntent: " + e.getMessage());
				}
			}
        });

        hello = (TextView) findViewById(R.id.hello);
        
        Intent intent = new Intent(MODULED_MODULES);
        List<ResolveInfo> list = getPackageManager().queryIntentActivities(intent, 0);
        
        String items[] = new String[list.size()];
        items_pkg = new String[list.size()];
        
        if(list.size() == 0) Log.w("list", "list is empty");
        
        for(int i = 0; i < list.size(); i++) {
        	ResolveInfo info = list.get(i);
        	items[i] = info.loadLabel(getPackageManager()).toString();
        	items_pkg[i] = info.activityInfo.packageName;
        }
        
        ListView listView = (ListView) findViewById(R.id.listView1);
        listView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items));
        listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
				Intent call = new Intent(MODULED_MODULES);
				call.setClassName(items_pkg[position], items_pkg[position] + ".MainActivity");
				startActivity(call);
			}
        	
        });
    }
    
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
    	switch(requestCode) {
    	case REQUEST_GET_TEXT:
    		if(resultCode != RESULT_OK) hello.setText("Result: Fail");
    		else hello.setText("Result: " + data.getStringExtra("text"));
    		break;
    	}
    }
}